package org.mm.service.impl;

import java.util.List;

import org.mm.model.Patient;
import org.mm.model.Therapy;
import org.mm.repository.TherapyRepository;
import org.mm.service.TherapyService;
import org.mm.web.controller.TherapyController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;


@Service("therapyService")
public class TherapyServiceImpl implements TherapyService {
	
	private final Logger log = LoggerFactory.getLogger(TherapyServiceImpl.class);	

	@Autowired
	private TherapyRepository therapyRepository;

	public List<Therapy> findTherapyByPatient(Patient patient) throws Exception {
		List<Therapy> therapies =  therapyRepository.findTherapyByPatientId(patient.getPatientId());
		return therapies;
	}

	public Therapy findTherapyByIdAndPatient(Long therapyId, Patient patient) throws Exception {
		Therapy therapy = therapyRepository.findTherapyByIdAndPatientId(therapyId, patient.getPatientId());
		return therapy;
	}
	
	
	@Transactional(readOnly = true)
	public List<Therapy> findAll() throws Exception {
		return Lists.newArrayList(therapyRepository.findAll(new Sort(Sort.Direction.ASC, "id")));
	}
	
	@Transactional(readOnly = true)
	public Therapy findById(Long id) throws Exception {
		return therapyRepository.findOne(id);
	}

	@Transactional
	public Therapy save(Therapy therapy) throws Exception {
		return therapyRepository.save(therapy);
	}

	@Transactional(readOnly = true)
	public Page<Therapy> findAllByPage(Pageable pageable) throws Exception {
		Page<Therapy> page = therapyRepository.findAll(pageable);
		clearLazyObjects(page.getContent());
		return page;
	}
	
	@Transactional(readOnly = true)
	public Page<Therapy> findAllByPage(Pageable pageable, Patient patient) throws Exception {
		Page<Therapy> page = therapyRepository.findTherapyByPatientId(pageable, patient.getPatientId());
		clearLazyObjects(page.getContent());
		return page;
	}
	
	private void clearLazyObjects(List<Therapy> therapies) {
		if (therapies != null) {
			for (Therapy t : therapies) {
				t.setTherapyTasks(null);
			}
		}
	}

	@Transactional
	public void delete(Therapy therapy) throws Exception {
		therapyRepository.delete(therapy);
	}
	
	@Transactional(readOnly = true)
	public Page<Therapy> search(Therapy therapy) throws Exception {
		Page<Therapy> page = null;
		/*		if (therapy.getId() != null) {
			PageRequest pageRequest 
			page = therapyRepository.findOne(pageRequest);
		}*/
		return page;
		
	}
}
